package com.shycloud.mido.member.service.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shycloud.common.minio.service.MinioTemplate;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.common.security.util.SecurityUtils;
import com.shycloud.mido.homework.api.vo.AtvActiveDetailItemVO;
import com.shycloud.mido.homework.api.vo.AtvActiveDetailReqVO;
import com.shycloud.mido.member.api.entity.AtvAttendDetail;
import com.shycloud.mido.member.api.entity.AtvMainActive;
import com.shycloud.mido.member.api.entity.AtvMediaSpace;
import com.shycloud.mido.member.api.entity.Member;
import com.shycloud.mido.member.api.util.Constant;
import com.shycloud.mido.member.api.util.DisplayConversionUtil;
import com.shycloud.mido.member.api.util.QrCodeUtil;
import com.shycloud.mido.member.api.util.UUIDUtil;
import com.shycloud.mido.member.api.vo.AtvMainActivePageVO;
import com.shycloud.mido.member.api.vo.AtvMainActiveReqVO;
import com.shycloud.mido.member.api.vo.AtvMainActiveRespVO;
import com.shycloud.mido.member.api.vo.AtvOptLocationVO;
import com.shycloud.mido.member.api.vo.OptOperatorVO;
import com.shycloud.mido.member.config.WXProperties;
import com.shycloud.mido.member.mapper.AtvAttendDetailMapper;
import com.shycloud.mido.member.mapper.AtvMainActiveMapper;
import com.shycloud.mido.member.mapper.MemberMapper;
import com.shycloud.mido.member.service.AtvAttendDetailService;
import com.shycloud.mido.member.service.AtvMainActiveService;
import com.shycloud.mido.opter.api.entity.OptOperator;
import com.shycloud.mido.opter.api.feign.RemoteOptService;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class AtvMainActiveServiceImpl extends ServiceImpl<AtvMainActiveMapper, AtvMainActive>
		implements AtvMainActiveService {

	@Autowired
	private MinioTemplate minioTemplate;
	@Autowired
	private WXProperties wXProperties;
	@Autowired
	private AtvAttendDetailMapper atvAttendDetailMapper;
	@Autowired
	private RemoteOptService remoteOptService;
	@Autowired
	private MemberMapper memberMapper;
	@Autowired
	private AtvMainActiveMapper atvMainActiveMapper;
	/** 活动详情模块 service */
	@Autowired
	private AtvAttendDetailService detailService;

	@Override
	public IPage<AtvMainActiveRespVO> pageAtvMainActiveRespVO(IPage<AtvMainActiveRespVO> page,
			AtvMainActivePageVO vo) {
		if (StringUtils.isNotBlank(vo.getMemberId())) {
			String memberId = SecurityUtils.getMember().getId();
			vo.setMemberId(memberId);
			if (BooleanUtils.isTrue(vo.isMyFlag())) {
				vo.setMyFlagString("=");
			} else {
				vo.setMyFlagString("!=");
			}
		}
		return baseMapper.pageAtvMainActiveRespVO(page, vo);
	}

	@Override
	public IPage<AtvMainActiveRespVO> pageAtvMainActiveRespVOTea(IPage<AtvMainActiveRespVO> page,
			AtvMainActivePageVO vo) {
		return baseMapper.pageAtvMainActiveRespVOTea(page, vo);
	}

	@Override
	public IPage<AtvMainActiveRespVO> pageAtvMainActiveRespVOStu(IPage<AtvMainActiveRespVO> page,
			AtvMainActivePageVO vo) {
		if (StringUtils.isNotBlank(vo.getMemberId())) {
			String memberId = SecurityUtils.getMember().getId();
			vo.setMemberId(memberId);
			if (BooleanUtils.isTrue(vo.isMyFlag())) {
				vo.setMyFlagString("EXISTS");
			} else {
				vo.setMyFlagString("NOT EXISTS");
			}
		}
		return baseMapper.pageAtvMainActiveRespVOStu(page, vo);
	}

	@Override
	public AtvMainActiveRespVO getAtvMainActiveRespVO(AtvMainActivePageVO vo) {
		return baseMapper.getAtvMainActiveRespVO(vo);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveOrUpdateAtvMainActive(AtvMainActiveReqVO vo) throws Exception {
		if (StringUtils.isBlank(vo.getId())) {
			// 保存输入校验
			AtvMainActive po = new AtvMainActive();
			BeanUtils.copyProperties(vo, po);
			// 默认设置
			po.setId(UUIDUtil.getUUID32());
			po.setPlayType("1");// 简单时间
			// po.setSource("0");//小程序
			po.setSponsorType("0");// 来源机构
			po.setStatus("0");// 正常
			// 通用
			Date now = new Date();
			po.setDelFlag(Constant.DEL_FLAG);
			po.setCreateTime(now);
			po.setUpdateTime(now);
			po.setCreateUser(vo.getMemberId());
			po.setUpdateUser(vo.getMemberId());
			// 二维码创建
			try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bosAttend = new ByteArrayOutputStream();) {
				byte[] createQrCode = QrCodeUtil.createQrCode(bos, wXProperties.getQrcodeHttp() + "?"
						+ "teacherMemberId=" + po.getMemberId() + "&mainActiveId=" + po.getId(), 1500, "PNG");
				ByteArrayInputStream is = new ByteArrayInputStream(createQrCode);
				// 调用OSS
				String uuid32 = UUIDUtil.getUUID32();
				String qrCodeUr = minioTemplate.uploadFileWX(is, Constant.BUCKET_QRCODE_PRE + uuid32,
						wXProperties.getQrcodeBucket(), wXProperties.getQrcodeCdn());
				// 新增报名二维码
				byte[] createQrAttendCode = QrCodeUtil.createQrCode(bosAttend, wXProperties.getQrcodeAttendHttp()
								+ "?" + "teacherMemberId=" + po.getMemberId() + "&mainActiveId=" + po.getId(), 1500,
						"PNG");
				ByteArrayInputStream isAttend = new ByteArrayInputStream(createQrAttendCode);
				// 调用OSS
				String qrCodeUrAttend =
						minioTemplate.uploadFileWX(isAttend, Constant.BUCKET_QRCODE_ATTEND_PRE + uuid32,
								wXProperties.getQrcodeBucket(), wXProperties.getQrcodeCdn());

				po.setQrCodeId(uuid32);
				po.setQrCodeUrl(qrCodeUr);
				po.setQrCodeAttendUrl(qrCodeUrAttend);
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				throw e;
			}

			this.save(po);
		} else {
			// 校验
			AtvMainActive atvMainActive = baseMapper.selectById(vo.getId());
			if (Objects.isNull(atvMainActive)) {
				throw new BusinessException("未查询到相关活动");
			}
			// 1未开始 2开启比赛 3进行中 4结束
			Integer status = this.queryMainActiveStatus(vo.getId());
			if (2 == status || 3 == status || 4 == status) {
				throw new BusinessException("活动中和已结束的活动无法修改");
			}
			// 更新
			LambdaUpdateWrapper<AtvMainActive> updateWrapper = Wrappers.<AtvMainActive>lambdaUpdate()
					.set(AtvMainActive::getTitle, vo.getTitle())
					.set(AtvMainActive::getSignupBeginDatetime, vo.getSignupBeginDatetime())
					.set(AtvMainActive::getProvince, vo.getProvince())
					.set(AtvMainActive::getCity, vo.getCity()).set(AtvMainActive::getArea, vo.getArea())
					.set(AtvMainActive::getOrgName, vo.getOrgName())
					.set(AtvMainActive::getPosterUrl, vo.getPosterUrl())
					.set(AtvMainActive::getUpdateTime, new Date())
					.set(AtvMainActive::getUpdateUser, vo.getMemberId()).eq(AtvMainActive::getId, vo.getId());
			this.update(updateWrapper);
		}
		return true;
	}

	@Override
	public IPage<AtvMainActiveRespVO> pageAtvMainActiveRespVONoSession(
			IPage<AtvMainActiveRespVO> page, AtvMainActivePageVO vo) {
		return baseMapper.pageAtvMainActiveRespVO(page, vo);
	}

	@Override
	public List<AtvActiveDetailItemVO> studentActiveDatail(AtvActiveDetailReqVO vo) {
		return baseMapper.studentActiveDatail(vo);
	}

	/**
	 * 1未开始 2开启比赛 3进行中 4结束
	 */
	@Override
	public Integer queryMainActiveStatus(String mainActiveId) {
		AtvMainActivePageVO vo = new AtvMainActivePageVO();
		vo.setId(mainActiveId);
		AtvMainActiveRespVO atvMainActiveRespVO = baseMapper.getAtvMainActiveRespVO(vo);
		if (Objects.isNull(atvMainActiveRespVO)) {
			throw new BusinessException("未查询到相关活动");
		}
		DisplayConversionUtil.transformOne(atvMainActiveRespVO);
		return Integer.valueOf(atvMainActiveRespVO.getDisplayStatus());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean logicDeleteAtv(String id) throws Exception {
		String memberId = SecurityUtils.getMember().getId();
		// 校验
		AtvMainActive atvMainActive = super.getById(id);
		if (Objects.isNull(atvMainActive)) {
			throw new BusinessException("未查询到相关活动");
		}
		// 1未开始 2开启比赛 3进行中 4结束
		Integer status = this.queryMainActiveStatus(id);
		if (2 == status || 3 == status || 4 == status) {
			throw new BusinessException("开启和已结束的活动无法删除");
		}
		LambdaUpdateWrapper<AtvMainActive> updateWrapper = Wrappers.<AtvMainActive>lambdaUpdate()
				.set(AtvMainActive::getDelFlag, Constant.DEL_FLAG_DELETE)// 软删除
				.set(AtvMainActive::getUpdateUser, memberId).set(AtvMainActive::getUpdateTime, new Date())
				.eq(AtvMainActive::getId, id);
		// 逻辑删除
		super.update(updateWrapper);// 解散报名
		LambdaQueryWrapper<AtvAttendDetail> deleteWrapper =
				Wrappers.<AtvAttendDetail>lambdaQuery().eq(AtvAttendDetail::getMainActiveId, id);

		List<AtvAttendDetail> atvAttendDetailList = atvAttendDetailMapper.selectList(deleteWrapper);
		if (CollectionUtils.isNotEmpty(atvAttendDetailList)) {
			log.info("解散报名：" + JSON.toJSONString(atvAttendDetailList));
			atvAttendDetailMapper.delete(deleteWrapper);
		}
		return true;
	}

	@Override
	public R pageByLocation(Page<AtvMainActiveRespVO> page, String province, String city, String memberId) {
		R<List<OptOperator>> r = remoteOptService.getDetailByLocation(province, city);
		if (Objects.nonNull(r) && CollectionUtils.isNotEmpty(r.getData())) {
			List<OptOperator> list = r.getData();
			OptOperator opt = list.get(0);
			String phone = opt.getPhone();
			if (StringUtils.isNotBlank(phone)) {
				//通过电话查询代理商的老师 在查询挑战赛
				LambdaQueryWrapper<Member> query = Wrappers.<Member>lambdaQuery().eq(Member::getUsername, phone)
						.eq(Member::getDelFlag, Constant.DEL_FLAG);
				Member member = memberMapper.selectOne(query);
				if (Objects.nonNull(member)) {
					AtvMainActivePageVO param = new AtvMainActivePageVO();
					param.setMemberId(member.getId());
					param.setMyFlagString("=");
					IPage<AtvMainActiveRespVO> pageAtvMainActiveRespVO = atvMainActiveMapper.pageAtvMainActiveRespVO(page, param);

					if (Objects.nonNull(pageAtvMainActiveRespVO) && CollectionUtils.isNotEmpty(pageAtvMainActiveRespVO.getRecords())) {
						if (StringUtils.isNotBlank(memberId)) {
							pageAtvMainActiveRespVO.getRecords().forEach(item -> {
								List<AtvAttendDetail> detailList = detailService
										.list(new QueryWrapper<AtvAttendDetail>()
												.eq(AtvAttendDetail.COL_MAIN_ACTIVE_ID, item.getId())
												.eq(AtvAttendDetail.COL_MEMBER_ID, memberId));

								if (detailList.size() > 0) {
									item.setIsMyJoin("1");
								} else {
									item.setIsMyJoin("0");
								}
								// 判断是否是参加此活动的教师
//              		if (StringUtils.isNotEmpty(teacherId)) {
//              			//判断是否跟其中一个学生有关联
//              			mainActive.setIsTeacherInAct(
//              					detailService.getIsTeacherInAct(mainActive.getId(), teacherId));
//              		}
							});
						}

						AtvOptLocationVO vo = new AtvOptLocationVO();
						OptOperatorVO optOperator = new OptOperatorVO();
						BeanUtils.copyProperties(opt, optOperator);
						vo.setAtvMainActiveRespVOList(pageAtvMainActiveRespVO.getRecords());
						vo.setOptOperator(optOperator);
						return new R(vo);
					}
				}
			}
		}
		return new R(CommonConstants.FAIL, "未找到相关活动", null);
	}


}

